﻿using System.Globalization;
using System.Xml.Linq;
using Microsoft.Xna.Framework;

namespace IcicleFramework.Components.Actions.ActionEffects
{
    public abstract class IntervalActionEffect : BaseActionEffect
    {
        public float IntervalTime { get; set; }

        public float TimeToNextInterval { get; protected set; }

        public override void Attached(IActionComponent target)
        {
            TimeToNextInterval = IntervalTime;

            base.Attached(target);
        }


        #region Constructors

        protected IntervalActionEffect() { }

        protected IntervalActionEffect(IntervalActionEffect old)
        {
            IntervalTime = old.IntervalTime;
        }

        #endregion


        public override void Update(GameTime gameTime)
        {
            TimeToNextInterval -= (float) gameTime.ElapsedGameTime.TotalSeconds;

            if (TimeToNextInterval <= 0f)
            {
                ApplyEffect();
            }

            base.Update(gameTime);
        }

        public override void Deserialize(XElement element)
        {
            float intervalTime = float.MaxValue;
            XElement intervalElement = element.Element("intervalTime");

            if (intervalElement != null)
            {
                float.TryParse(intervalElement.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out intervalTime);
            }
            IntervalTime = intervalTime;

            base.Deserialize(element);
        }
    }
}
